package cn.jdy.plugins.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.Column;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.FileDownLoadThread;
import cn.jdy.framework.util.FileUtil;
import cn.jdy.framework.util.HttpUtil;
import cn.jdy.framework.util.IDUtil;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.ConfService;
import cn.jdy.platform.service.NewsService;

import cn.jdy.plugins.entity.RobotLinks;
import cn.jdy.plugins.entity.RobotManager;


/**
 * @title 新闻信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/news")
public class NewsCtrl extends BaseCtrl {

	@Autowired
	private NewsService newsService;
	@Autowired
	private ConfService confService;
	//默认列表路径
	private static String viewName = "redirect:/news/list?s=";
	

	

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(News entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/newsList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList", confService.queryByType(4, 0L));
		return mv;
	}
	
	/**
	 * 特警
	 * 初始化
	 * @return
	 */
	@RequestMapping("/lists")
	public ModelAndView lists(News entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/newsLists.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList", confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		return mv;
	}

	/**
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(News news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", newsService.query(news, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", newsService.count(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询新闻异常", e);
		}
		return jsonMap;
	}

	/**
	 * 特警
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPages")
	@ResponseBody
	public Map<String, Object> queryByPages(News news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", newsService.query(news, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", newsService.count(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询新闻异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}
	
	/**
	 * 特警
	 * 新增
	 * @return
	 */
	@RequestMapping("/edits")
	public ModelAndView edits() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/newsDetail.jsp");
		mv.addObject("column", this.confService.queryByType(4, 0L));
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		return mv;
	}
	
	/**
	 * 特警
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edits/{id}")
	public ModelAndView edits(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/newsDetails.jsp");
		mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(News news, Long pid) {
		ModelAndView mv = new ModelAndView();
		//将数组转化成String
		String[] ds=news.getDepartments();
		String deps = "";
		for(int i=0;i<46;i++){
			if(ds[i]==null || ds[i]=="")ds[i]=";";
			deps += ","+ds[i];
		}
		news.setDepars(deps);
		news.setDepartments(null);
		//
		try {
			//如果二级新闻类别为空，则使用一级类别
	      if(null == news.getColumnId()) {
	        news.setColumnId(pid);
	      }
			if(news.getId()==null) {// 新增文章
				//
				User user = getUser();
				news.setUserid(user.getId());
				news.setUsername(user.getUsername());
				//市局需要手动更改时间，如果为空则取正确时间
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
//				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.newsService.save(news);
				mv.setViewName(this.viewName.concat("1"));
			} else {//更新文章
				User user = getUser();
				news.setUserid(user.getId());
				news.setUsername(user.getUsername());
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}//市局
				this.newsService.update(news);
				mv.setViewName(this.viewName.concat("2"));
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "新闻保存异常！", e);
		}

		return mv;
	}
	
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
      NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除新闻异常！", e);
		}
		return mv;
	}
	
	/**
	 * 特警
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/dels/{id}")
	public ModelAndView dels(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/news/lists");
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
      NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除新闻异常！", e);
		}
		return mv;
	}
	
	/**
	 * 置顶/在原置顶基础上再次点击，即换为有效状态
	 * @param id
	 * @return
	 */
	@RequestMapping("/stickie/{id}")
	public ModelAndView reset(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/newsList.jsp");
			if(id!=null && id!=0){
				List<News> resultSet = this.newsService.queryStickieNews();
				int len = resultSet.size();
				News news = this.newsService.find(id);
				Long columnID = news.getColumnId();
				String crtStatus = news.getStatus();
				if(!crtStatus.equals("3")){
					int cnt=0;
					for(int i=0;i<len;i++){
						if(resultSet.get(i).getColumnId() == columnID) cnt++;
					}
					if(cnt==0){//保证一类新闻中只有一条新闻能被置顶
						news.setStatus("3");//置顶
					}
				}
				if(crtStatus.equals("3")){
					news.setStatus("1");//取消置顶，即换成有效状态
				}
				this.newsService.update(news);
			}
		return mv;
	}

	/**
	 * 市公安局
	 * 复签：只需要发布者一人签收
	 * 未复签时，签收状态为有效状态“1”
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/counterSign/{id}")
	public ModelAndView ctsigned(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/newsList.jsp");
		News data = this.newsService.find(id);
		if(name.equals(data.getUsername())){
			data.setStatus("4");//已复签
		}
		this.newsService.update(data);
		return mv;
	}
	
	/**
	 * 特警
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/saves")
	public ModelAndView savet(News news, Long pid) {
		ModelAndView mv = new ModelAndView("/news/lists");
		try {
			//如果二级新闻类别为空，则使用一级类别
      if(null == news.getColumnId()) {
        news.setColumnId(pid);
      }
			if(news.getId()==null) {// 新增文章
				User user = getUser();
				news.setUserid(user.getId());
				news.setUsername(user.getUsername());
				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				//底层service是falseCreateTime排序
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.newsService.save(news);
				mv.setViewName(this.viewName.concat("1"));
			} else {//更新文章
				this.newsService.update(news);
				mv.setViewName(this.viewName.concat("2"));
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "新闻保存异常！", e);
		}

		return mv;
	}
	
	 
	  /**
	   * 解析出超链接
	   * @param s 待解析的内容
	   * @param url 
	   * @param must
	   * @return
	   */
	  public static List<Map<String, Object>> getLinkli(final String s, final String url,String must) {
	      String regex;
	      final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	      regex = "<li>[\\s\\S].*?</li>";
	      final Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
	      final Matcher ma = pa.matcher(s);
	      while (ma.find()) {
	      	Map<String, Object> linkMap = new HashMap<String, Object>();
	          String href = ma.group(2);
	          if(href.indexOf(must)==-1){//必须包含
	            continue;// 跳出本次循环，继续下次循环
	          }
	          if(href.matches("(http|https)://.*")){
	          	linkMap.put("href", href);
	          	linkMap.put("title", ma.group(5));
	          	list.add(linkMap);
	          } else {
	          	Pattern p = Pattern.compile("(http://|https://)?([^/]*)",Pattern.CASE_INSENSITIVE);
	          	Matcher matcher = p.matcher(url);
	          	matcher.find();
	          	if (href.indexOf("/") != 0) {
	          		linkMap.put("href", matcher.group()+"/"+href);
	          	} else {
	          		linkMap.put("href", matcher.group()+href);
	          	}
	          	linkMap.put("title", ma.group(5));
	          	list.add(linkMap);
	          }
//	            BaseLog.d(RobotManagerCtrl.class, "整个链接==>"+ma.group());
//	            BaseLog.d(RobotManagerCtrl.class, "链接地址==>"+ma.group(2)); 
//	            BaseLog.d(RobotManagerCtrl.class, "链接标题==>"+ma.group(5));
	      }
	      return list;
	  }
	  /**
	   * @return 获取指定区域的内容
	   * <div class=\"partbox\">(.*?)<div class=\"con_right\">
	   */
	  public static String getAreaContent(String s,String startFlag,String endFlag) {
	      // 获取指定区域的内容
	      final Pattern pa = Pattern.compile(startFlag+"(.*?)"+endFlag, Pattern.DOTALL);  
	      final Matcher ma = pa.matcher(s);  
	      StringBuffer sb = new StringBuffer(); 
	      
	      while (ma.find()) {  
	          sb.append(ma.group(1));
	      }  
	      return sb.toString();
	  }
	/**
	   * 抽取文本中的图片并下载到本地
	   * @param text
	   * @param access_path 图片访问地址前缀
	   * @param location_path 图片存储路径
	   * @return
	   * @throws Exception
	   */
	 public static Map<String, String> dywatchImg(String text,String text2,String text3) throws Exception{
		    // 抓出图片地址 替换图片标示
		    Map mp=new  HashMap<>();
		   String ql=text.substring(0, 2)+"00";
		    
		        String imgUrl = "http://www.12348.gov.cn/imagetype/"+ql+"/lsfw/lsuser/"+text2.split("\\.")[0]+"/jpg";
		        if(imgUrl.matches("(http|https)://.*")){
		            // 获取文件格式后缀 组成本地文件保存路径
		      //  String dd="http://www.falvweiyun.com/attachment/images/120/2018/02/FnT5KZ7X5bTBkXNKFztnT5B7ZbHK0G.jpg";
		        //    String suffix = "."+dd.replaceAll("^.*\\.", "");
		          //  System.out.println(suffix);
		            // 将匹配到的内容 替换为既定的表现形式
		            //String uploadImgurl = FileUtil.getFilePath("/upload/fltx",".jpg");
		      String uploadImgurl="/upload/fltx/"+DateUtil.getCurrentDate3()+"/"+text3+".jpg";
		            mp.put("imgpath", uploadImgurl);
		            // 下载图片到既定位置 upload/doc/年月日/md5.jpg
		            // 启动下载线程异步下载 
		            GlobalConstant.uploadPool.execute(new FileDownLoadThread(imgUrl, GlobalConstant.PROJECT_WEBAPPS_PATH + uploadImgurl));
		        }
		  
		    return mp;
		  }
	 public static void main(String[] args) throws Exception {
		 dywatchImg("36","2017070714581708754.jpg","13601201710838940");
	
	}
	
}
